/*
* Copyright 1993-2010 NVIDIA Corporation.  All rights reserved.
*
* NOTICE TO USER:
*
* This source code is subject to NVIDIA ownership rights under U.S. and
* international Copyright laws.  Users and possessors of this source code
* are hereby granted a nonexclusive, royalty-free license to use this code
* in individual and commercial software.
*
* NVIDIA MAKES NO REPRESENTATION ABOUT THE SUITABILITY OF THIS SOURCE
* CODE FOR ANY PURPOSE.  IT IS PROVIDED "AS IS" WITHOUT EXPRESS OR
* IMPLIED WARRANTY OF ANY KIND.  NVIDIA DISCLAIMS ALL WARRANTIES WITH
* REGARD TO THIS SOURCE CODE, INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE.
* IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL,
* OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
* OF USE, DATA OR PROFITS,  WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
* OR OTHER TORTIOUS ACTION,  ARISING OUT OF OR IN CONNECTION WITH THE USE
* OR PERFORMANCE OF THIS SOURCE CODE.
*
* U.S. Government End Users.   This source code is a "commercial item" as
* that term is defined at  48 C.F.R. 2.101 (OCT 1995), consisting  of
* "commercial computer  software"  and "commercial computer software
* documentation" as such terms are  used in 48 C.F.R. 12.212 (SEPT 1995)
* and is provided to the U.S. Government only as a commercial end item.
* Consistent with 48 C.F.R.12.212 and 48 C.F.R. 227.7202-1 through
* 227.7202-4 (JUNE 1995), all U.S. Government End Users acquire the
* source code with only those rights set forth herein.
*
* Any use of this source code in individual and commercial software must
* include, in the user documentation and internal comments to the code,
* the above Disclaimer and U.S. Government End Users Notice.
*/


#include <cuda.h>

#include <iostream>
#include <string>
#include <vector>

#include <windows.h>

#include "../../../Common/check.h"

////////////////////////////////////////////////////////////////////////////////
// Initialization Code
////////////////////////////////////////////////////////////////////////////////

bool ShouldGetUserInput(int argc, wchar_t** argv)
{
    for(int i = 1; i < argc; i++)
    {
        if (wcscmp(argv[i], L"noprompt") == 0)
        {
            return false;
        }
    }

    return true;
}

bool PrintDevices(int cudaDeviceOrdinalForCuContext)
{
    CUresult status = CUDA_ERROR_UNKNOWN;
    int deviceCount = 0;

    status = cuDeviceGetCount(&deviceCount);
    CheckConditionXR(CUDA_SUCCESS == status, false);

    for (int curDeviceId = 0; curDeviceId < deviceCount; ++curDeviceId)
    {
        CUdevice curCuDevice;
        status = cuDeviceGet(&curCuDevice, curDeviceId);
        CheckConditionXR(CUDA_SUCCESS == status, false);

        std::wcout << L"device" << curDeviceId << std::endl;

        char nameBuf[128];
        status = cuDeviceGetName(nameBuf, sizeof(nameBuf), curCuDevice);
        CheckConditionXR(CUDA_SUCCESS == status, false);

        std::wcout <<"    Name = " << nameBuf;
        if (cudaDeviceOrdinalForCuContext == curDeviceId)
        {
            std::wcout << L"    <------  Creating CUcontext on this";
        }
        std::wcout << std::endl;

		//Returns the compute capability of the device.
		int major,minor;
		status = cuDeviceComputeCapability (&major, &minor, curCuDevice);
		std::wcout << "    Compute Capability = " << major << '.' << minor << std::endl;
 	 
		//Returns the total amount of memory on the device.
		size_t totalmem;
		status =cuDeviceTotalMem (&totalmem, curCuDevice);
		std::wcout << "    Total Memory = " << totalmem << std::endl;
 	
		//Get Attributes
        int attribValue;

		status = cuDeviceGetAttribute(&attribValue, CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK, curCuDevice);
        CheckConditionXR(CUDA_SUCCESS == status, false);
        std::wcout << "    Shared Memory Per Block = " <<  attribValue << std::endl;

		status = cuDeviceGetAttribute(&attribValue, CU_DEVICE_ATTRIBUTE_TOTAL_CONSTANT_MEMORY, curCuDevice);
        CheckConditionXR(CUDA_SUCCESS == status, false);
        std::wcout << "    Total Constant Memory = " <<  attribValue << std::endl;

        status = cuDeviceGetAttribute(&attribValue, CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT, curCuDevice);
        CheckConditionXR(CUDA_SUCCESS == status, false);
        std::wcout << "    SMCount = " <<  attribValue << std::endl;

        status = cuDeviceGetAttribute(&attribValue, CU_DEVICE_ATTRIBUTE_CLOCK_RATE, curCuDevice);
        CheckConditionXR(CUDA_SUCCESS == status, false);
        std::wcout << "    ClockRate = " << attribValue << std::endl;

		//Get Properties
		CUdevprop prop;
		status = cuDeviceGetProperties(&prop, curCuDevice);
        CheckConditionXR(CUDA_SUCCESS == status, false);

		std::wcout << "    maxThreadsPerBlock = " << prop.maxThreadsPerBlock << std::endl;
		std::wcout << "    maxThreadsDim = " << prop.maxThreadsDim[0] << ' ' << prop.maxThreadsDim[1] << ' ' << prop.maxThreadsDim[2] << std::endl;

    }

    return true;
}

//  Create stand-alone CUcontext.  (One that does not use D3D or OpenGL interop.)
bool CreateCudaContext(int cudaDeviceOrdinal, CUdevice* pDevice, CUcontext* pContext)
{
    CUfunction cuFunction = 0;
    CUresult status = CUDA_ERROR_UNKNOWN;
    bool br = false;

    br = PrintDevices(cudaDeviceOrdinal);
    CheckConditionXR(br, false);

    int deviceCount = 0;
    status = cuDeviceGetCount(&deviceCount);
    CheckConditionXR(CUDA_SUCCESS == status, false);

    //  Ensure cudaDeviceOrdinal corresponds to a valid device #.
    CheckConditionXR(cudaDeviceOrdinal < deviceCount, false);

    status = cuDeviceGet(pDevice, cudaDeviceOrdinal);
    CheckConditionXR(CUDA_SUCCESS == status, false);

    unsigned int flags = 0;
    status = cuCtxCreate( pContext, flags, *pDevice );
    CheckConditionXR(CUDA_SUCCESS == status, false);

    return true;
}

bool LoadMatrixMulModule(CUmodule* pModule, CUdevice dev, const std::wstring& applicationDir)
{
    CUresult status = CUDA_ERROR_UNKNOWN;

    *pModule = 0;

    std::vector<char> moduleFullpath;
    moduleFullpath.resize(applicationDir.length() + 1);
    moduleFullpath[applicationDir.length()] = 0;

    ::WideCharToMultiByte(CP_UTF8, 0, applicationDir.c_str(), -1, &moduleFullpath[0], (int)applicationDir.length(), 0, 0);

    std::string modulePath(&moduleFullpath[0]);
    modulePath += "matrixMul_kernel.cubin";

    status = cuModuleLoad(pModule, modulePath.c_str());
    if (status == CUDA_ERROR_INVALID_SOURCE)
    {
        fprintf(stderr, "FAILED: cuModuleLoad(\"%s\") returned status=CUDA_ERROR_INVALID_SOURCE.\n", modulePath.c_str());
        fprintf(stderr, "\nMost likely the cubin file does not match the device's SM#.  Try recompiling for a different architecture.\n");

        int major = 0, minor = 0;
        CUresult statusComputeCap = cuDeviceComputeCapability(&major, &minor, dev);
        if (statusComputeCap == CUDA_SUCCESS)
        {
            fprintf(stderr, "CUdevice arch=SM%d.%d\nTry setting CodeGeneration to arch=compute_%d%d,code=sm_%d%d\n",
                major, minor, major, minor, major, minor);
        }
        fprintf(stderr, "Press a key to continue ...");
        getchar();

        return false;
    }
    else if (status != CUDA_SUCCESS)
    {
        fprintf(stderr, "FAILED: cuModuleLoad(\"%s\") returned status=%d\n",
            modulePath.c_str(), status);

        fprintf(stderr, "Press a key to continue ...");
        getchar();
        return false;
    }

    CheckConditionXR(CUDA_SUCCESS == status, false);

    return true;
}
